package reserve
import (
    "time"
	"strings"
	"errors"
	"dhfshop/models"
	"github.com/astaxie/beego/orm"
)

//可预约时间段,专属每一个peroid，可以单独更改，不影响其他peroid
type Timeslot struct {
	TimeslotId    int64        `orm:"column(timeslot_id);pk;auto" json:"timeslot_id" form:"timeslot_id"`
	PartnerId     int64          `orm:"column(partner_id)" json:"partner_id" form:"partner_id"`
	Schema        *Schema      `orm:"column(schema_id);rel(fk);on_delete(cascade)" json:"-" form:"-"`      //级联删除
	SchemaId      int64        `orm:"-" json:"schema_id" form:"schema_id"`
	TimeslotNo    int          `orm:"column(timeslot_no)" json:"timeslot_no" form:"timeslot_no"`           //时段序号
	TimeslotLabel string       `orm:"column(timeslot_label)" json:"timeslot_label" form:"timeslot_label"`  //时段标签
	Period        *Period      `orm:"column(period_id);rel(fk);on_delete(cascade)" json:"-"`               //级联删除
    PeriodId      int64        `orm:"-" json:"period_id" form:"period_id"`
    SourceAt      time.Time    `orm:"column(source_at);type(date)" json:"-" form:"-"` //号源时间,只要日期到天
    SourceAtStr   string       `orm:"-" json:"source_at" form:"source_at"`
	Start         string       `orm:"column(start);null" json:"start" form:"start"` //开始时间,非全日期时间,比如: 11:00
	End           string       `orm:"column(end);null" json:"end" form:"end"`       //结束时间,非全日期时间,比如: 12:00
	CurCount      int          `orm:"column(cur_count)" json:"cur_count" form:"cur_count"`  //当前预约量(每个peroid都可能不同)
	MaxCount      int          `orm:"column(max_count)" json:"max_count" form:"max_count"`  //最大可预约量
	Status        int          `orm:"column(status);default(1)" json:"status" form:"status"` //是否有效: 1 有效; 0 无效
}

func init() {
	orm.RegisterModel(new(Timeslot))
}

func AddTimeslot(m *Timeslot) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func AddMultiTimeslots(list []*Timeslot) (err error) {
	size := len(list)
	o := models.GetDefaultDB()
	if size > 1 {
	    _, err = o.InsertMulti(size, list) 
	}else{
	   _, err = o.Insert(list[0])
	}
	return
}

func GetTimeslotById(id int64) (v *Timeslot, err error) {
	o := models.GetDefaultDB()
	v = &Timeslot{TimeslotId: id}
	if err = o.Read(v); err == nil {
		v.SchemaId = v.Schema.SchemaId
		v.PeriodId = v.Period.PeriodId
		v.Schema = nil
		v.Period = nil
		return v, nil
	}
	return nil, err
}
//查询所有餐桌
func GetAllTimeslots(query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*Timeslot, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Timeslot))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	var lists []*Timeslot
	qs = qs.OrderBy(sortFields...)
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		for _, timeslot := range lists {
			timeslot.SchemaId = timeslot.Schema.SchemaId
			timeslot.PeriodId = timeslot.Period.PeriodId
			timeslot.Schema = nil
			timeslot.Period = nil
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func GetTimeslotIdsByPeriods(partnerId,schemaId int64,periodIds []int64)(timeslotIds []int64, err error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Timeslot))
	qs = qs.Filter("partner_id", partnerId)
	qs = qs.Filter("schema_id", schemaId)
	if len(periodIds) > 0 {
        qs = qs.Filter("period_id__in", periodIds)
    }
	var lists []*Timeslot
	if _, err = qs.All(&lists); err == nil {
		for _, timeslot := range lists {
			timeslotIds = append(timeslotIds, timeslot.TimeslotId)
	    }
		return
	}
	return
}

func UpdateTimeslotById(m *Timeslot, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := Timeslot{TimeslotId: m.TimeslotId}
	if err = o.Read(&v); err != nil {
		return err
	}else{
	    if _, err = o.Update(m, k...); err != nil {
		   return err
		}
	}
	return nil
}
func DeleteTimeslot(id int64) (err error) {
	o := models.GetDefaultDB()
	v := Timeslot{TimeslotId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}

func DeleteTimeslotByMultiCond(partnerId, periodId, timeslotId int64) (err error) {
    o := models.GetDefaultDB()
	qs := o.QueryTable(new(Timeslot))
	qs = qs.Filter("partner_id", partnerId)
	if periodId > 0 {
	   qs = qs.Filter("period_id", periodId)
	}
	if timeslotId > 0 {
	   qs = qs.Filter("timeslot_id", timeslotId)
	}
	_, err = qs.Delete()
	return
}
